package com.July.controller;

import com.July.mapper.DepartmentMapper;
import com.July.mapper.EmployeeMapper;
import com.July.pojo.Department;
import com.July.pojo.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Collection;

@Controller
public class EmployeeController {
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private DepartmentMapper departmentMapper;
    @RequestMapping("/emps")
    public String List(Model model){
        Collection<Employee> employees = employeeMapper.getAll();
        for (Employee employee : employees) {
            employee.setDepartment(departmentMapper.getDepartmentById(employee.getDepartmentId()));
            System.out.println(employee.toString());
        }

        model.addAttribute("employees",employees);
        return "emp/list";
    }

    @GetMapping("/emp")
    public String toAddpage(Model model){
        //查出所有部门的信息
        Collection<Department> departments=departmentMapper.getDepartments();
        model.addAttribute("departments",departments);
        return "emp/add";
    }
    @PostMapping("/emp")
    public String addEmp(Employee employee){
        //添加的操作
        System.out.println("sqve===============>"+employee);
        employeeMapper.save(employee);
        return "redirect:/emps";
    }

    //去员工的修改页面
    @GetMapping("/emp/{id}")
    public String toUpdatePage(@PathVariable("id")Integer id,Model model){
        //查出原来的数据
        Employee employeeById = employeeMapper.getEmployeeById(id);
        System.out.println(employeeById);
        employeeById.setDepartment(departmentMapper.getDepartmentById(employeeById.getDepartmentId()));
        model.addAttribute("emp",employeeById);
        Collection<Department> departments=departmentMapper.getDepartments();
        for (Department department : departments) {
            System.out.println(department.toString());
        }
        model.addAttribute("departments",departments);
        return "emp/update";
    }
    //修改员工信息
    @PostMapping("/UpdateEmp")
    public String updateEmp(Employee employee){
        employee.setDepartmentId(employee.getDepartment().getId());
        employeeMapper.updateEmployee(employee);
        return "redirect:/emps";
    }

    //删除员工
    @GetMapping("/delemp/{id}")
    public String deleteEmp(@PathVariable("id")Integer id){
        employeeMapper.delEmployee(id);
        return "redirect:/emps";
    }
}
